#include "xmlparser.h"
#include <QDebug>

XMLParser::XMLParser(QObject *parent) :
    QObject(parent)
{
}

void XMLParser::parseData(QByteArray data){

	QXmlStreamReader xml( data );

	while(!xml.atEnd() && !xml.hasError()){
		xml.readNext();

		if(xml.isStartDocument()) {
			continue;
		}

		//rozpoznajemy tylko te 3 elementy, reszte ignorujemy(o ile coś takiego się pojawi)
		if(xml.isStartElement() &&
		   xml.name() == QString::fromUtf8("item")){
				parseItem(xml);
			}

	}

	if (xml.hasError() && xml.error()
		!= QXmlStreamReader::PrematureEndOfDocumentError) {
		qWarning() << "XML ERROR:" << xml.lineNumber() <<
				": " << xml.errorString();
	   // http.abort();
	}

}

void XMLParser::parseItem(QXmlStreamReader &reader){
	reader.readNext();//omijamy tag otwierajacy "Aktorzy"
	item newItem;
	while( !(reader.isEndElement() &&
			 reader.name() == QString::fromUtf8("item")) ) {
		if(reader.isStartElement()){
			if(reader.name()==QString::fromUtf8("title")){
				newItem.title = reader.readElementText();
				qDebug()<<"title:"<<newItem.title;
			}
			if(reader.name()==QString::fromUtf8("description")){
				newItem.description = reader.readElementText();
				qDebug()<<"description:"<<newItem.description;
			}
			if(reader.name()==QString::fromUtf8("link")){
				newItem.link = reader.readElementText();
				qDebug()<<"link:"<<newItem.link;
			}
			if(reader.name()==QString::fromUtf8("guid")){
				newItem.guid = reader.readElementText();
				qDebug()<<"guid:"<<newItem.guid;
			}
			if(reader.name()==QString::fromUtf8("pubDate")){
				newItem.pubDate = reader.readElementText();
				qDebug()<<"pubDate:"<<newItem.pubDate;
			}

		}
		reader.readNext();
	}
	//FIXME
	//insertItem(newItem);
}
